package com.ray.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.ray.bean.ApprovalBean;
import com.ray.bean.AttendApprovalProcessBean;
import com.ray.bean.AuditLoggingBean;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.ReportBean;
import com.ray.bean.TableData;
import com.ray.bean.UserBean;
import com.ray.exception.ServiceException;
import com.ray.mapper.ApprovalMapper;
import com.ray.mapper.DingTalkMapper;
import com.ray.util.ReturnStringUtil;
import com.ray.util.StringUtil;

import net.sf.json.JSONArray;

@Service
public class ApprovalService {
	@Autowired
	ApprovalMapper approvalMapper;
	@Autowired
	WorkshopService workshopService;
	@Autowired
	UserService userService;
	@Autowired
	DingTalkMapper dingTalkMapper;

	//获取登录者可以审核的人员
	public List<String> getApprovalIdByLoginId(Map map) {
		return approvalMapper.getApprovalIdByLoginId(map);
	}
	
	/**
	 * 获取登录者的审核人
	* @date 2018年5月31日 下午6:39:07 
	* @author 李斌
	* @return List<String> 
	* @throws 
	 */
	public List<String> getApprovalUserIdByLoginUserId(Map map){
		return approvalMapper.getApprovalUserIdByLoginUserId(map);
	};

	//审批通过报工
	public String approvalReport(Map map) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String time=sdf.format(new Date());
		map.put("time", time);
		String id=map.get("id").toString();
		int status=Integer.parseInt(map.get("status").toString());
		String docMakePeopleId=workshopService.getTouchPeople(id);
		AuditLoggingBean auditLoggingBean=new AuditLoggingBean();
		auditLoggingBean.setApprovalId(id);//被审核报工数据id
		auditLoggingBean.setApprovalPeople(map.get("loginUserId").toString());//审核人id
		auditLoggingBean.setApprovalTime(time);//审核时间
		auditLoggingBean.setApprovalType(2);//审核类型  报工
		auditLoggingBean.setDocMakePeople(docMakePeopleId);//制单人
		auditLoggingBean.setId(StringUtil.getUUID());//id
		auditLoggingBean.setRemark(map.get("approvalReason").toString());//备注
		auditLoggingBean.setStatus(status);//状态设为通过
		String result=workshopService.approvalReport(map);
		approvalMapper.insertAuditLogging(auditLoggingBean);
		String returnStr="";
		if(status==1) {
			returnStr= ReturnStringUtil.APPROVAL_SUCCESS + result;
		}
		if(status==2) {
			returnStr= ReturnStringUtil.RETURN_SUCCESS + result;
		}
		return returnStr;
	}

	public String allApprovalReport(Map map) throws CloneNotSupportedException {
		List<AuditLoggingBean> listLogg=new ArrayList<AuditLoggingBean>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String time=sdf.format(new Date());
		map.put("time", time);
		String idArray=map.get("id").toString();
		JSONArray jsonArray = JSONArray.fromObject(idArray);
		List<ReportBean> reportList=(List<ReportBean>) JSONArray.toCollection(jsonArray, ReportBean.class);
		List<String> idList=reportList.stream().map(ReportBean::getTypeId).collect(Collectors.toList());
		map.put("idList", idList);
		map.put("reportList", reportList);
		int status=Integer.parseInt(map.get("status").toString());
		AuditLoggingBean auditLoggingBean=new AuditLoggingBean();
		auditLoggingBean.setApprovalPeople(map.get("loginUserId").toString());//审核人id
		auditLoggingBean.setApprovalTime(time);//审核时间
		auditLoggingBean.setApprovalType(2);//审核类型  报工
		auditLoggingBean.setRemark(map.get("approvalReason").toString());//备注
		auditLoggingBean.setStatus(status);//状态
		for(String id:idList) {
			AuditLoggingBean aa=auditLoggingBean.clone();
			String docMakePeopleId=workshopService.getTouchPeople(id);
			aa.setApprovalId(id);//被审核报工数据id
			aa.setDocMakePeople(docMakePeopleId);//制单人
			aa.setId(StringUtil.getUUID());//id
			listLogg.add(aa);
		}
		String xx=workshopService.approvalAllReport(map);
		approvalMapper.insertAllAuditLogging(listLogg);
		String returnStr="";
		if(status==1) {
			returnStr= ReturnStringUtil.APPROVAL_SUCCESS+xx;
		}
		if(status==2) {
			returnStr= ReturnStringUtil.RETURN_SUCCESS+xx;
		}
		return returnStr;
	}

	//获取审批数据
	public DatatablesViewPageBean getApproval(Map map) {
		DatatablesViewPageBean<ApprovalBean> dtcpb=new DatatablesViewPageBean<ApprovalBean>();
		int count=0;
		count=approvalMapper.getApprovalCount(map);
		//获取前十个人的权限
		List<ApprovalBean> approvalList=approvalMapper.getApproval(map);
		
        //整理后的审批权限
		List<ApprovalBean>  beanList=approvalMapper.getApprovalPeopleList(approvalList);
		for(ApprovalBean approvalBean :approvalList) {
           //每个人的审批人员列表
			List<String> peopleList=beanList.stream().filter(pp->pp.getProject().equals(approvalBean.getProject()) && pp.getName().equals(approvalBean.getName())).map(ApprovalBean::getUserName).collect(Collectors.toList());
			List<String> peopleIdList=beanList.stream().filter(pp->pp.getProject().equals(approvalBean.getProject()) && pp.getName().equals(approvalBean.getName())).map(ApprovalBean::getUserId).collect(Collectors.toList());
			approvalBean.setApprovalUserList(peopleList);
			approvalBean.setApprovalUserIdList(peopleIdList);
		}
		dtcpb.setReturnData(approvalList);
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}

	//修改审批
//	public Map update(Map map) throws ServiceException {
//		UserBean userBean=userService.getUserByName(map);
//		map.put("id", userBean.getId());
//		List<String> haveIdList=approvalMapper.getHaveId(map);
//		List<UserBean> haveUserList=null;
//				userService.getHaveUser(haveIdList);
//		map.put("idList", haveIdList);
//		List<UserBean> noHaveUserList=null;
//				userService.getNoHaveUser(map);
//		Map returnMap=new HashMap();
//		returnMap.put("haveUserList", haveUserList);
//		returnMap.put("noHaveUserList", noHaveUserList);
//		return returnMap;
//	}

//	public void updateRemove(Map map) throws ServiceException {
//		UserBean userBean=userService.getUserByName(map);
//		map.put("id", userBean.getId());
//		String idArray=map.get("idArray").toString();
//		JSONArray jsonArray = JSONArray.fromObject(idArray);
//		List<String> idList=jsonArray.subList(0, jsonArray.size());
//		map.put("idList", idList);
//	    approvalMapper.updateRemove(map);
//	}
	
//	//添加修改
//	public void updateAdd(Map map) throws ServiceException {
//		UserBean userBean=userService.getUserByName(map);
//		map.put("id", userBean.getId());
//		String idArray=map.get("idArray").toString();
//		JSONArray jsonArray = JSONArray.fromObject(idArray);
//		List<String> idList=jsonArray.subList(0, jsonArray.size());
//		map.put("idList", idList);
//	    approvalMapper.updateAdd(map);
//	}

	/**
	 * 修改审核设置
	 * addName (添加的审核人)
	 * addProject (添加审核类型)
	 * idArray (被审核的用户id)
	 * updateName (被修改的审核人)
	 * updateProject (被修改的类型)
	 * @param map
	 */
	public void  updateApproval(Map map) {
		StringUtil.checkIsTrue(map, "addName", "未获取到审核人");
		StringUtil.checkIsTrue(map, "addProject", "未获取到审核类型");
		StringUtil.checkIsTrue(map, "idArray", "未获取到被审核人");
		StringUtil.checkIsTrue(map, "updateName", "未获取到修改之前审核人");
		StringUtil.checkIsTrue(map, "updateProject", "未获取到修改之前类型审核人");
        this.delete(map);
		this.addApperval(map);
	}
	
	/**
	 * 添加审批类型
	 * @param map
	 * @throws ServiceException
	 */
	public void addApperval(Map map) throws ServiceException {
		List<ApprovalBean> approvalBeanList=approvalMapper.findApproval(map);
		Assert.isTrue(approvalBeanList.size()<=0,ReturnStringUtil.APPROVAL_ALREADY_EXCEPTION);
		String idArray=map.get("idArray").toString();
		JSONArray jsonArray = JSONArray.fromObject(idArray);
		List<String> idList=jsonArray.subList(0, jsonArray.size());
		map.put("idList", idList);
		int row=approvalMapper.addApperval(map);
		Assert.isTrue(row>0,"添加失败");
	}

	//删除审批
	public void delete(Map map) throws ServiceException {
		int row=approvalMapper.delete(map);
		Assert.isTrue(row>0,"删除失败");
	}

	/**  
	 * Title: addApprovalProcess
	 * Description: TODO(这里用一句话描述这个方法的作用)  
	 * @param map  
	 * @author 王荣
	 * @date 2018年6月23日 上午9:59:43
	 */ 
	@SuppressWarnings("unchecked")
	public void addApprovalProcess(Map<String,Object> map) {
		List<AttendApprovalProcessBean> attendApprovalProcessBeanList=dingTalkMapper.findApprovalProcess(map);
		if(attendApprovalProcessBeanList.size()>0) {
			throw new ServiceException("审批已存在");
		}
		String idArray=map.get("idArray").toString();
		JSONArray jsonArray = JSONArray.fromObject(idArray);
		List<String> idList=jsonArray.subList(0, jsonArray.size());
		map.put("idList", idList);
		dingTalkMapper.addApprovalProcess(map);
	}

	/**
	 * 获取可审核登录人的用户名称
	 * @param map
	 * @return
	 */
	public List<String> getApprovalUserBeanByLoginUserId(Map map) {
		// TODO Auto-generated method stub
		return approvalMapper.getApprovalUserBeanByLoginUserId(map);
	}

	/**
	 * 校验是否可以自己审核自己
	 * @param map
	 * @return
	 */
	public boolean checkSelfApprovalPermission(Map map) {
		boolean bool=true;
		List<ApprovalBean> list=approvalMapper.checkSelfApprovalPermission(map);
		if(null==list || list.size()<=0) {
			bool=false;
		}
		return bool;
	}

}
